tic

compname = getenv('computername');

if strcmp(compname,'DESKTOP-BHR0AU7')
    % datadir = 'E:\ANL\Experiments\DATA\VAST\PREPROCESSED\ERP_alternate_analyses\ERP_winlevelBL\';
    datadir = 'E:\ANL\Experiments\DATA\VAST\PREPROCESSED\ERP\';
    savedir = 'E:\ANL\Experiments\RESULTS\VAST\EEG\';
    addpath('C:\Users\jtjus\Documents\MATLAB\fieldtrip-20180512\fieldtrip-20180512');
    addpath(genpath('E:\MATLAB\CSDtoolbox'));
elseif strcmp(compname,'MSI')
    % datadir = 'E:\ANL\PREPROCESSED_DATA\VAST\ERP_alternate_analyses\ERP_winlevelBL\';
    datadir = 'E:\ANL\PREPROCESSED_DATA\VAST\ERP\';
    savedir = 'E:\ANL\RESULTS\VAST\EEG\';
    addpath('D:\MATLAB\fieldtrip-20180809\fieldtrip-20180809');
    addpath(genpath('D:\MATLAB\CSDtoolbox'));
else
    error('need to set up paths for this machine.')
end

allERPfiles = dir(datadir);
allERPfiles = extractfield(allERPfiles, 'name');
allERPfiles = allERPfiles(3:end);
sIDs = cellfun(@(x) x(1:end-2), allERPfiles, 'UniformOutput', false);
sIDs = unique(sIDs);
Nss = length(sIDs);
Nchans = 64;
Ntpts = 155;

standardConds = {'as_as','as_at','as_none','at_as','at_at','at_none',...
    'vs_as','vs_at','vs_none','vt_as','vt_at','vt_none'};
Nconds = length(standardConds);
allERPtypes = {'enc_s1','enc_s2','enc_s3','enc_s4','int_s1','int_s2',...
    'int_s3','ret_s1','ret_s2','ret_s3','ret_s4'};
Ntypes = length(allERPtypes);
allERPtypes_noInt = allERPtypes(~contains(allERPtypes,'int'));
Ntypes_noInt = length(allERPtypes_noInt);
% For averaging over first 3 ERPs in each window
ERPtypes_red = {'enc','int','ret'};
Ntypes_red = length(ERPtypes_red);
ERPtypes_red_noInt = {'enc','ret'};
Ntypes_red_noInt = length(ERPtypes_red_noInt);

% Preallocate for averages
[avg, sem, avg3, sem3] = deal([standardConds; cell(1,12)]);
for i = 1:Nconds
    if contains(avg{1,i}, 'none') % no interfering conditions 
        [avg{2,i}, sem{2,i}] = deal([allERPtypes_noInt; cell(1,Ntypes_noInt)]);
        [avg3{2,i}, sem3{2,i}] = deal([ERPtypes_red_noInt; cell(1,Ntypes_red_noInt)]);
    else % condition with an interfering task
        [avg{2,i}, sem{2,i}] = deal([allERPtypes; cell(1,Ntypes)]);
        [avg3{2,i}, sem3{2,i}] = deal([ERPtypes_red; cell(1,Ntypes_red)]);
    end     
    [avg{2,i}(2,:), sem{2,i}(2,:), avg3{2,i}(2,:), sem3{2,i}(2,:)] =... 
     deal({zeros(Nchans, Ntpts)});
end

%% Main loop for averaging

cfg = [];

for c = 1:Nconds
    currcond = standardConds{c};
    
    % Preallocate for all subjects data at each ERP position
    if contains(currcond, 'none') % no interfering task
        looptypes = allERPtypes_noInt;
        ind = cell(1, Ntypes_noInt);
        looptypes_r = ERPtypes_red_noInt;
        ind3 = cell(1, Ntypes_red_noInt); 
    else % interfering task is present
        looptypes = allERPtypes;
        ind = cell(1, Ntypes);
        looptypes_r = ERPtypes_red;
        ind3 = cell(1, Ntypes_red); 
    end
    [ind(:), ind3(:)] = deal({zeros(Nchans, Ntpts, Nss)});

    for s = 1:Nss
        % Load this subject's data
        id = sIDs{s};
        erp_A = load(strcat(datadir,id,'_a\',id,'_a_avgERPs.mat'));
        erp_A = erp_A.avgERPs;
        erp_V = load(strcat(datadir,id,'_v\',id,'_v_avgERPs.mat'));
        erp_V = erp_V.avgERPs;
        
        % Specifically data in the current condition
        if strcmp(currcond(1),'a') % auditory memory task
            % pull all ERP types in this cond
            data = erp_A{2, strcmp(erp_A(1,:), currcond)};
        elseif strcmp(currcond(1),'v') % visual memory task
            % pull all ERP types in this cond
            data = erp_V{2, strcmp(erp_V(1,:), currcond)};
        end

        % LOOP OVER ERP TYPES
        for erp = 1:length(looptypes)
            currtype = looptypes{erp};
            ind{erp}(:,:,s) = data{3, strcmp(data(1,:), currtype)};
        end
        % average of first 3
        for erp = 1:length(looptypes_r)
            inds = contains(data(1,:), looptypes_r{erp}) &...
                ~contains(data(1,:),'4');
            all3 = cat(3, data{3,inds});
            ind3{erp}(:,:,s) = mean(all3, 3);
        end
            
    end % subject loop

    %% Compute grand averages within this condition
    
    % Loop over ERP types again
    for erp = 1:length(looptypes)
        avg{2,c}{2,erp} = mean(ind{erp}, 3);
        for t = 1:Ntpts
            sem{2,c}{2,erp}(:,t) = std(ind{erp}(:,t,:), 0, 3) / sqrt(Nss);
        end
        % clear individual subjects data (no longer needed)
        ind{erp} = [];
    end
    
    % Same for average of first 3 ERPs in each window
    for erp = 1:length(looptypes_r)
        avg3{2,c}{2,erp} = mean(ind3{erp}, 3);
        for t = 1:Ntpts
            sem3{2,c}{2,erp}(:,t) = std(ind3{erp}(:,t,:), 0, 3) / sqrt(Nss);
        end
        % clear individual subjects data (no longer needed)
        ind3{erp} = [];
    end

end % condition loop

save(strcat(savedir,'avg_eachERP'),'avg','sem','avg3','sem3','-v7.3');

toc

